package com.xhs.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhs.model.QrCodeResult;
import com.xhs.model.SearchTask;
import com.xhs.mapper.QrCodeResultMapper;
import com.xhs.mapper.SearchTaskMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 二维码结果数据库操作Manager
 *
 * @author xhs
 */
@Service
public class QrCodeResultManager extends ServiceImpl<QrCodeResultMapper, QrCodeResult> {

    @Autowired
    private SearchTaskMapper searchTaskMapper;

    /**
     * 根据任务ID查询结果列表
     *
     * @param taskId 任务ID
     * @return 结果列表
     */
    public List<QrCodeResult> findByTaskId(Long taskId) {
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getTaskId, taskId)
                .eq(QrCodeResult::getDeleted, 0)
                .orderByDesc(QrCodeResult::getScanTime);
        return this.list(queryWrapper);
    }

    /**
     * 根据用户ID查询结果列表
     *
     * @param userId 用户ID
     * @return 结果列表
     */
    public List<QrCodeResult> findByUserId(Long userId) {
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getUserId, userId)
                .eq(QrCodeResult::getDeleted, 0)
                .orderByDesc(QrCodeResult::getScanTime);
        return this.list(queryWrapper);
    }

    /**
     * 根据手机号查询结果列表
     *
     * @param phoneNumber 手机号
     * @return 结果列表
     */
    public List<QrCodeResult> findByPhoneNumber(String phoneNumber) {
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getPhoneNumber, phoneNumber)
                .eq(QrCodeResult::getDeleted, 0)
                .orderByDesc(QrCodeResult::getScanTime);
        return this.list(queryWrapper);
    }

    /**
     * 分页查询结果列表
     *
     * @param userId   用户ID
     * @param pageNum  页码
     * @param pageSize 页大小
     * @return 分页结果
     */
    public IPage<QrCodeResult> findByUserIdWithPage(Long userId, int pageNum, int pageSize) {
        Page<QrCodeResult> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getUserId, userId)
                .eq(QrCodeResult::getDeleted, 0)
                .orderByDesc(QrCodeResult::getScanTime);
        return this.page(page, queryWrapper);
    }

    /**
     * 根据任务ID分页查询结果
     *
     * @param taskId   任务ID
     * @param pageNum  页码
     * @param pageSize 页大小
     * @return 分页结果
     */
    public IPage<QrCodeResult> findByTaskIdWithPage(Long taskId, int pageNum, int pageSize) {
        Page<QrCodeResult> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getTaskId, taskId)
                .eq(QrCodeResult::getDeleted, 0)
                .orderByDesc(QrCodeResult::getScanTime);
        return this.page(page, queryWrapper);
    }

    /**
     * 根据关键词查询结果
     *
     * @param userId  用户ID
     * @param keyword 关键词
     * @return 结果列表
     */
    public List<QrCodeResult> findByKeyword(Long userId, String keyword) {
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getUserId, userId)
                .eq(QrCodeResult::getKeyword, keyword)
                .eq(QrCodeResult::getDeleted, 0)
                .orderByDesc(QrCodeResult::getScanTime);
        return this.list(queryWrapper);
    }



    /**
     * 根据时间范围查询结果
     *
     * @param userId    用户ID
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 结果列表
     */
    public List<QrCodeResult> findByTimeRange(Long userId, LocalDateTime startTime, LocalDateTime endTime) {
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getUserId, userId)
                .ge(QrCodeResult::getScanTime, startTime)
                .le(QrCodeResult::getScanTime, endTime)
                .eq(QrCodeResult::getDeleted, 0)
                .orderByDesc(QrCodeResult::getScanTime);
        return this.list(queryWrapper);
    }

    /**
     * 保存二维码结果
     *
     * @param qrCodeResult 二维码结果
     * @return 是否成功
     */
    public boolean saveResult(QrCodeResult qrCodeResult) {
        qrCodeResult.setCreateTime(LocalDateTime.now());
        qrCodeResult.setUpdateTime(LocalDateTime.now());
        qrCodeResult.setDeleted(0);
        return this.save(qrCodeResult);
    }

    /**
     * 检查二维码是否已存在
     *
     * @param taskId     任务ID
     * @param qrCodeUrl  二维码URL
     * @return 是否存在
     */
    public boolean existsByTaskIdAndQrCodeUrl(Long taskId, String qrCodeUrl) {
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getTaskId, taskId)
                .eq(QrCodeResult::getQrCodeUrl, qrCodeUrl)
                .eq(QrCodeResult::getDeleted, 0);
        return this.count(queryWrapper) > 0;
    }

    /**
     * 批量保存二维码结果
     *
     * @param qrCodeResults 二维码结果列表
     * @return 是否成功
     */
    public boolean batchSaveResults(List<QrCodeResult> qrCodeResults) {
        LocalDateTime now = LocalDateTime.now();
        qrCodeResults.forEach(result -> {
            result.setCreateTime(now);
            result.setUpdateTime(now);
            result.setDeleted(0);
        });
        return this.saveBatch(qrCodeResults);
    }

    /**
     * 根据任务ID统计结果数量
     *
     * @param taskId 任务ID
     * @return 结果数量
     */
    public long countByTaskId(Long taskId) {
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getTaskId, taskId)
                .eq(QrCodeResult::getDeleted, 0);
        return this.count(queryWrapper);
    }

    /**
     * 根据用户ID统计结果数量
     *
     * @param userId 用户ID
     * @return 结果数量
     */
    public long countByUserId(Long userId) {
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getUserId, userId)
                .eq(QrCodeResult::getDeleted, 0);
        return this.count(queryWrapper);
    }

    /**
     * 根据任务ID删除结果（软删除）
     *
     * @param taskId 任务ID
     */
    public void deleteByTaskId(Long taskId) {
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getTaskId, taskId);
        
        List<QrCodeResult> results = this.list(queryWrapper);
        for (QrCodeResult result : results) {
            result.setDeleted(1);
            result.setUpdateTime(LocalDateTime.now());
        }
        
        if (!results.isEmpty()) {
            this.updateBatchById(results);
        }
    }



    /**
     * 根据任务名称分页查询结果
     *
     * @param userId 用户ID
     * @param taskName 任务名称
     * @param pageNum 页码
     * @param pageSize 页大小
     * @return 分页结果
     */
    public IPage<QrCodeResult> findByTaskNameWithPage(Long userId, String taskName, int pageNum, int pageSize) {
        // 先根据任务名称和用户ID查询任务
        LambdaQueryWrapper<SearchTask> taskQueryWrapper = new LambdaQueryWrapper<>();
        taskQueryWrapper.eq(SearchTask::getUserId, userId)
                .eq(SearchTask::getTaskName, taskName)
                .eq(SearchTask::getDeleted, 0);
        SearchTask task = searchTaskMapper.selectOne(taskQueryWrapper);
        
        if (task == null) {
            // 如果任务不存在，返回空结果
            return new Page<>(pageNum, pageSize);
        }
        
        // 根据任务ID查询结果
        Page<QrCodeResult> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<QrCodeResult> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(QrCodeResult::getTaskId, task.getId())
                .eq(QrCodeResult::getDeleted, 0)
                .orderByDesc(QrCodeResult::getScanTime);
        
        return this.page(page, queryWrapper);
    }
} 